package com.ruoyi.flowable.listener.scrap;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.EquAsset;
import com.ruoyi.equ.domain.EquScrap;
import com.ruoyi.equ.service.IEquAssetService;
import com.ruoyi.equ.service.IEquScrapService;
import com.ruoyi.flowable.domain.WorkOrderAssetRel;
import com.ruoyi.flowable.service.IWorkOrderAssetRelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ruoyi.flowable.listener.asset.AssetCompleteListener.*;
import static com.ruoyi.flowable.listener.asset.AssetListener_2.getFileList;

/**
 * 报废-完成监听
 */
@Slf4j
@Component("scrapCompleteListener")
public class ScrapCompleteListener implements ExecutionListener {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final IEquScrapService scrapService = SpringUtils.getBean(IEquScrapService.class);
    private static final IEquAssetService assetService = SpringUtils.getBean(IEquAssetService.class);
    private static final IWorkOrderAssetRelService workOrderAssetRelService = SpringUtils.getBean(IWorkOrderAssetRelService.class);

    @Override
    public void notify(DelegateExecution execution) {
        try {
            //正式报废日期
            Date scrapDate = sdf.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            //台账保留期限

            //创建者
            String createBy = SecurityUtils.getLoginUser().getUser().getNickName();

            //备注
            String assetName = execution.getVariable("assetName", String.class);
            String scrapReason = execution.getVariable("scrapReason", String.class);
            String remark = assetName + scrapReason + "报废";

            //资产状态
            EquScrap equScrap = execution.getVariable("equScrap", EquScrap.class);
            equScrap.setScrapDate(scrapDate);
            equScrap.setCreateBy(createBy);
            equScrap.setRemark(remark);

            //新增
            scrapService.insertEquScrap(equScrap);
            //修改资产状态：报废
            EquAsset equAsset = new EquAsset();
            equAsset.setAssetId(equScrap.getAssetId());
            equAsset.setAssetStatus("已报废");
            assetService.updateEquAsset(equAsset);

            //更新状态
            String processInstanceId = execution.getProcessInstanceId();
            WorkOrderAssetRel workOrderAssetRel = new WorkOrderAssetRel();
            workOrderAssetRel.setProcInsId(processInstanceId);
            workOrderAssetRel.setWorkOrderStatus("已完成");
            workOrderAssetRel.setFinishTime(new Date());
            //生成word
            String url = generateWord(execution.getVariables(), equScrap);
            workOrderAssetRel.setFileUrl(url);
            workOrderAssetRelService.updateWorkOrderAssetRel(workOrderAssetRel);
        } catch (ParseException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String generateWord(Map<String, Object> variables, EquScrap equScrap) throws IOException {
        // 读取resources目录下的文件
        BufferedInputStream resourceAsStream = new BufferedInputStream(
                Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("word/医院设备报废申请表.docx"))
        );
        // 使用配置编译模板
        XWPFTemplate template = XWPFTemplate.compile(resourceAsStream);
        Configure config = template.getConfig();

        HashMap<String, Object> finalMap = new HashMap<>();
        finalMap.put("申请单号", equScrap.getScrapId());//scrap_id
        finalMap.put("申请日期", sdfTime.format(equScrap.getCreateTime()));

        finalMap.put("设备名称", variables.get("assetName"));
        finalMap.put("设备型号规格", variables.get("modelSpec"));
        finalMap.put("资产编号", variables.get("assetNumber"));
        finalMap.put("生产厂家", variables.get("manufacturer"));
        finalMap.put("购置日期", variables.get("purchaseDate"));
        finalMap.put("购置金额", variables.get("purchaseAmount"));
        finalMap.put("累计折旧金额", variables.get("accumulatedDepreciation"));
        finalMap.put("资产账面净值", variables.get("bookValue"));
        finalMap.put("使用科室", variables.get("useDept"));
        finalMap.put("主要用途", variables.get("purpose"));
        finalMap.put("使用年限", variables.get("serviceLife"));
        finalMap.put("实际使用时长", variables.get("actualServiceTime"));

        //TODO 其他：xxx
        String scrapReason = variables.get("scrapReason").toString();
        if (scrapReason.equals("设备老化")) finalMap.put("报废原因1", "☑");
        else finalMap.put("报废原因1", "□");
        if (scrapReason.equals("故障频发")) finalMap.put("报废原因2", "☑");
        else finalMap.put("报废原因2", "□");
        if (scrapReason.equals("技术落后")) finalMap.put("报废原因3", "☑");
        else finalMap.put("报废原因3", "□");
        if (scrapReason.equals("损坏严重")) finalMap.put("报废原因4", "☑");
        else finalMap.put("报废原因4", "□");
        if (scrapReason.equals("政策不符")) finalMap.put("报废原因5", "☑");
        else finalMap.put("报废原因5", "□");
        if (scrapReason.equals("其他")) finalMap.put("报废原因6", "☑ 其他：" + variables.get("otherReason"));
        else finalMap.put("报废原因6", "□ 其他");

        //1
        String repairTime1 = variables.get("repairTime1").toString();
        String repairContent1 = variables.get("repairContent1").toString();
        String repairCost1 = variables.get("repairCost1").toString();
        if (StringUtils.isNotEmpty(repairTime1) && StringUtils.isNotEmpty(repairContent1) && StringUtils.isNotEmpty(repairCost1)) {
            finalMap.put("维修历史1时间", "a.\t" + repairTime1 + "，");
            finalMap.put("维修历史1内容", repairContent1 + "，");
            finalMap.put("维修历史1费用", "费用 " + repairCost1 + "元");
        }
        //2
        String repairTime2 = variables.get("repairTime2").toString();
        String repairContent2 = variables.get("repairContent2").toString();
        String repairCost2 = variables.get("repairCost2").toString();
        if (StringUtils.isNotEmpty(repairTime2) && StringUtils.isNotEmpty(repairContent2) && StringUtils.isNotEmpty(repairCost2)) {
            finalMap.put("维修历史2时间", "\nb.\t" + repairTime2 + "，");
            finalMap.put("维修历史2内容", repairContent2 + "，");
            finalMap.put("维修历史2费用", "费用 " + repairCost2 + "元");
        }
        //3
        String repairTime3 = variables.get("repairTime3").toString();
        String repairContent3 = variables.get("repairContent3").toString();
        String repairCost3 = variables.get("repairCost3").toString();
        if (StringUtils.isNotEmpty(repairTime3) && StringUtils.isNotEmpty(repairContent3) && StringUtils.isNotEmpty(repairCost3)) {
            finalMap.put("维修历史3时间", "\nc.\t" + repairTime3 + "，");
            finalMap.put("维修历史3内容", repairContent3 + "，");
            finalMap.put("维修历史3费用", "费用 " + repairCost3 + "元");
        }

        finalMap.put("外观描述", variables.get("appearanceDesc"));
        finalMap.put("功能描述", variables.get("functionDesc"));

        List<Map<String, String>> statusImages = (List<Map<String, String>>) variables.get("statusImages");
        if (CollectionUtils.isNotEmpty(statusImages)) {
            finalMap.put("现状照片content", "\n现状照片：");
        }
        for (int i = 0; i < statusImages.size(); i++) {
            finalMap.put("现状照片" + (i + 1), Pictures.ofLocal(replaceUrl(statusImages.get(i).get("url"))).size(200, 80).create());
            config.customPolicy("现状照片" + (i + 1), new PictureRenderPolicy());
        }

        //显示图片，文档链接
        List<Map<String, String>> contractFiles = (List<Map<String, String>>) variables.get("contractFiles");
        for (int i = 0; i < contractFiles.size(); i++) {
            String fileUrl = contractFiles.get(i).get("url");
            String fileName = fileUrl.toLowerCase();
            // 使用正则表达式匹配图片文件
            if (fileName.matches(".*\\.(jpg|jpeg|png|gif|bmp|tiff|tif|webp|svg)$")) {
                finalMap.put("购买合同" + (i + 1), Pictures.ofLocal(replaceUrl(contractFiles.get(i).get("url"))).size(200, 80).create());
                config.customPolicy("购买合同" + (i + 1), new PictureRenderPolicy());
            } else {
                finalMap.put("合同content" + (i + 1), "文档链接：");
                finalMap.put("购买合同" + (i + 1), contractFiles.get(i).get("previewUrl"));
            }
        }

        List<Map<String, String>> repairFiles = (List<Map<String, String>>) variables.get("repairFiles");
        for (int i = 0; i < repairFiles.size(); i++) {
            String fileUrl = repairFiles.get(i).get("url");
            String fileName = fileUrl.toLowerCase();
            // 使用正则表达式匹配图片文件
            if (fileName.matches(".*\\.(jpg|jpeg|png|gif|bmp|tiff|tif|webp|svg)$")) {
                finalMap.put("历次维修记录单" + (i + 1), Pictures.ofLocal(replaceUrl(repairFiles.get(i).get("url"))).size(200, 80).create());
                config.customPolicy("历次维修记录单" + (i + 1), new PictureRenderPolicy());
            } else {
                finalMap.put("维修content" + (i + 1), "文档链接：");
                finalMap.put("历次维修记录单" + (i + 1), repairFiles.get(i).get("previewUrl"));
            }
        }

        List<Map<String, String>> testFiles = (List<Map<String, String>>) variables.get("testFiles");
        for (int i = 0; i < testFiles.size(); i++) {
            String fileUrl = testFiles.get(i).get("url");
            String fileName = fileUrl.toLowerCase();
            // 使用正则表达式匹配图片文件
            if (fileName.matches(".*\\.(jpg|jpeg|png|gif|bmp|tiff|tif|webp|svg)$")) {
                finalMap.put("设备检测报告" + (i + 1), Pictures.ofLocal(replaceUrl(testFiles.get(i).get("url"))).size(200, 80).create());
                config.customPolicy("设备检测报告" + (i + 1), new PictureRenderPolicy());
            } else {
                finalMap.put("报告content" + (i + 1), "文档链接：");
                finalMap.put("设备检测报告" + (i + 1), testFiles.get(i).get("previewUrl"));
            }
        }

        int index = 0;
        //5.1
//        if (ObjectUtils.isNotEmpty(variables.get("signature_act2_1"))) {
//            index++;
//            finalMap.put("使用科室title" + index, index + ".\t使用科室意见：\n");
//            finalMap.put("审批人content" + index, "经核实，该设备上述情况属实，确需报废，同意提交申请。\n审批人签字：");
//            List<Map<String, String>> signature_act2_1 = (List<Map<String, String>>) variables.get("signature_act2_1");
//            finalMap.put("审批人签字" + index, Pictures.ofLocal(replaceUrl(signature_act2_1.get(0).get("url"))).size(200, 80).create());
//            config.customPolicy("审批人签字" + index, new PictureRenderPolicy());
//            finalMap.put("使用负责人content", "\n使用负责人签字：");
//            List<Map<String, String>> leaderSign_act2_1 = (List<Map<String, String>>) variables.get("leaderSign_act2_1");
//            finalMap.put("使用负责人签字", Pictures.ofLocal(replaceUrl(leaderSign_act2_1.get(0).get("url"))).size(200, 80).create());
//            config.customPolicy("使用负责人签字", new PictureRenderPolicy());
//            finalMap.put("日期content" + index, "\n日期：");
//            finalMap.put("日期" + index, variables.get("date2_1"));
//        }

        if (ObjectUtils.isNotEmpty(variables.get("signature_act2_2"))) {
            index++;
            if (index != 1) {
                finalMap.put("title" + index, "\n" + index + ".\t资产管理部门审核意见：\n");
            } else {
                finalMap.put("title" + index, index + ".\t资产管理部门审核意见：\n");
            }
            finalMap.put("审批人content" + index, "已现场核查设备状况，确认符合报废条件，同意推进。\n审批人签字：");
            List<Map<String, String>> signature_act2_2 = (List<Map<String, String>>) variables.get("signature_act2_2");
            finalMap.put("审批人签字" + index, Pictures.ofLocal(replaceUrl(signature_act2_2.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("审批人签字" + index, new PictureRenderPolicy());
            finalMap.put("日期content" + index, "\n日期：");
            finalMap.put("日期" + index, variables.get("date2_2"));
        }

//        if (ObjectUtils.isNotEmpty(variables.get("signature_act2_3"))) {
//            index++;
//            if (index != 1) {
//                finalMap.put("title" + index, "\n" + index + ".\t财务部门审核意见：\n");
//            } else {
//                finalMap.put("title" + index, index + ".\t财务部门审核意见：\n");
//            }
//            finalMap.put("审批人content" + index, "已核对该设备账目，审核结果：" + variables.get("checkRes4") + "，折旧计提符合财务制度，同意报废。\n审批人签字：");
//            List<Map<String, String>> signature_act2_3 = (List<Map<String, String>>) variables.get("signature_act2_3");
//            finalMap.put("审批人签字" + index, Pictures.ofLocal(replaceUrl(signature_act2_3.get(0).get("url"))).size(200, 80).create());
//            config.customPolicy("审批人签字" + index, new PictureRenderPolicy());
//            finalMap.put("日期content" + index, "\n日期：");
//            finalMap.put("日期" + index, variables.get("date2_3"));
//        }

        if (ObjectUtils.isNotEmpty(variables.get("signature_act2_4"))) {
            index++;
            if (index != 1) {
                finalMap.put("title" + index, "\n" + index + ".\t技术评估小组意见：\n");
            } else {
                finalMap.put("title" + index, index + ".\t技术评估小组意见：\n");
            }
            finalMap.put("评估组长签字content", "经技术评估，该设备" + variables.get("flag5") + "，建议报废。\n评估组长签字：");
            List<Map<String, String>> signature_act2_4 = (List<Map<String, String>>) variables.get("signature_act2_4");
            finalMap.put("评估组长签字", Pictures.ofLocal(replaceUrl(signature_act2_4.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("评估组长签字", new PictureRenderPolicy());
            //成员签字
            List<Map<String, String>> member_sign_1 = (List<Map<String, String>>) variables.get("member_sign_1");
            List<Map<String, String>> member_sign_2 = (List<Map<String, String>>) variables.get("member_sign_2");
            List<Map<String, String>> member_sign_3 = (List<Map<String, String>>) variables.get("member_sign_3");
            int count = 0;
            if (CollectionUtils.isNotEmpty(member_sign_1)) {
                count++;
                finalMap.put("成员签字content", "\n成员签字：");
                finalMap.put("技术成员" + count + "签字", Pictures.ofLocal(replaceUrl(member_sign_1.get(0).get("url"))).size(200, 80).create());
                config.customPolicy("技术成员" + count + "签字", new PictureRenderPolicy());
            }
            if (CollectionUtils.isNotEmpty(member_sign_2)) {
                count++;
                finalMap.put("成员签字content", "\n成员签字：");
                finalMap.put("技术成员" + count + "签字", Pictures.ofLocal(replaceUrl(member_sign_2.get(0).get("url"))).size(200, 80).create());
                config.customPolicy("技术成员" + count + "签字", new PictureRenderPolicy());
            }
            if (CollectionUtils.isNotEmpty(member_sign_3)) {
                count++;
                finalMap.put("成员签字content", "\n成员签字：");
                finalMap.put("技术成员" + count + "签字", Pictures.ofLocal(replaceUrl(member_sign_3.get(0).get("url"))).size(200, 80).create());
                config.customPolicy("技术成员" + count + "签字", new PictureRenderPolicy());
            }

            finalMap.put("技术评估日期content", "\n日期：");
            finalMap.put("技术评估日期", variables.get("date2_4"));
        }

        String flag6 = variables.get("flag6").toString();
        if (flag6.equals("同意")) {
            finalMap.put("主管审批1", "☑");
            finalMap.put("主管审批2", "□");
        } else {
            finalMap.put("主管审批1", "□");
            finalMap.put("主管审批2", "☑");
        }
        List<Map<String, String>> signature_act3 = (List<Map<String, String>>) variables.get("signature_act3");
        finalMap.put("主管副院长签字", Pictures.ofLocal(replaceUrl(signature_act3.get(0).get("url"))).size(200, 80).create());
        config.customPolicy("主管副院长签字", new PictureRenderPolicy());
        finalMap.put("主管副院长签字日期", variables.get("date3_3"));

        String flag = variables.get("flag").toString();
        //${flag=="大型设备"}
        if (flag.equals("大型设备")) {
            finalMap.put("院长title", "\n2.\t院长审批：\n");
            finalMap.put("院长审批", "同意报废，按规定办理后续处置手续。");
            finalMap.put("content1", "\n签字：");
            finalMap.put("content2", "\n日期：");
            List<Map<String, String>> signature_act3_1 = (List<Map<String, String>>) variables.get("signature_act3_1");
            finalMap.put("院长签字", Pictures.ofLocal(replaceUrl(signature_act3_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("院长签字", new PictureRenderPolicy());
            finalMap.put("院长签字日期", variables.get("date3_1"));
        }

        template.render(finalMap);
        // 生成临时文件
        String tempFileName = "设备报废单_" + variables.get("assetNumber") + "_" + System.currentTimeMillis() + ".docx";
        File tempFile = new File(System.getProperty("java.io.tmpdir"), tempFileName);

        try {
            template.writeToFile(tempFile.getAbsolutePath());
            log.info("Word文档生成成功，临时文件路径: {}", tempFile.getAbsolutePath());
            // 上传文件
            return uploadWordFile(tempFile, tempFileName);
            //本地路径
//            String wordPath = "D:\\项目学习\\若依工作流\\word\\aa.docx";
//            template.writeToFile(wordPath);
//            System.out.println("Word文档生成成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            template.close();

        }
    }
}
